package marchsoft.modules.selfFish.pisciculture.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.selfFish.pisciculture.entity.Health;
import marchsoft.modules.selfFish.pisciculture.entity.dto.HealthDto;
import marchsoft.modules.selfFish.pisciculture.entity.vo.HealthVo;
import marchsoft.modules.selfFish.pisciculture.mapper.HealthMapper;
import marchsoft.modules.selfFish.pisciculture.service.HealthService;
import marchsoft.modules.system.entity.SysRelationFile;
import marchsoft.modules.system.service.ISysRelationFileService;
import marchsoft.response.Result;
import marchsoft.utils.FileUtils;
import marchsoft.utils.LocalDateTimeUtils;
import marchsoft.utils.SecurityUtils;
import marchsoft.utils.ServiceType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 *@title HealthServiceImpl
 *@description
 *@author Lenovo
 *@version 1.0
 *@create 2024-07-15 17:24
 */
@Service
@Slf4j
public class HealthServiceImpl extends ServiceImpl<HealthMapper, Health> implements HealthService {

    @Autowired
    private HealthMapper healthMapper;

    @Autowired
    private HealthService healthService;

    @Autowired
    private ISysRelationFileService sysRelationFileService;
    @Override
    public Result<Object> getHealthList(String fishName, Long pageNum, Long pageSize) {
        IPage<HealthVo> healthList = healthMapper.getHealthList(new Page<>(pageNum, pageSize), fishName);
        healthList.getRecords().forEach(healthVo -> {
            QueryWrapper<SysRelationFile>qw = new QueryWrapper<>();
            qw.eq("service_id",healthVo.getId());
            qw.eq("status","1");
            qw.eq("service_type", ServiceType.HEALTH);
            List<SysRelationFile> list = sysRelationFileService.list(qw);
            if(list != null && list.size()>0){
                healthVo.setFileId(list.get(0).getId());
            }

        });
        return Result.success(healthList);
    }

    @Override
    public Result<Object> create(HealthDto healthDto) {
        Health health = new Health();
        BeanUtils.copyProperties(healthDto,health);
        health.setCreatedUserId(SecurityUtils.getCurrentUserId());
        health.setCreatedTime(LocalDateTime.now());
        if(healthMapper.insert(health)>0){
            //附件保存
            sysRelationFileService.saveFile(healthDto.getFileId(),health.getId(),ServiceType.HEALTH);
            log.info(StrUtil.format("【添加鱼群健康成功】操作人id：{}，新增目标healtht：{}", SecurityUtils.getCurrentUserId(), healthDto));
            return Result.success("新增成功！");
        };
        return Result.error("新增失败！");
    }

    @Override
    public Result<Object> delete(Set<Long> ids) {
        UpdateWrapper<Health> uw = new UpdateWrapper<>();
        uw.in("id",ids)
                .set("status",false);
        if(healthService.update(uw)){
            //删除附件
            sysRelationFileService.deleteFile(new ArrayList<>(ids),ServiceType.HEALTH);
            log.info(StrUtil.format("【删除鱼群健康成功】操作人id：{}，删除目标healthts：{}", SecurityUtils.getCurrentUserId(), ids.toString()));
            return Result.success("删除成功！");
        };
        return Result.error("删除失败！");
    }

    @Override
    public Result<Object> update(HealthDto healthDto) {
        Health health = getById(healthDto.getId());
        if (ObjectUtil.isEmpty(health)) {
            log.error(StrUtil.format("【修改鱼群健康失败】操作人id：{}，修改目标health为空，目标healthId：{}", SecurityUtils.getCurrentUserId(), health.getId()));
            throw new BadRequestException("修改失败，当前数据id不存在");
        }
        if(health.getCreatedUserId()!=SecurityUtils.getCurrentUserId()){
            log.error(StrUtil.format("【修改鱼群健康失败】操作人id：{}，目标health新增人id：{}", SecurityUtils.getCurrentUserId(), health.getCreatedUserId()));
            throw new BadRequestException("该鱼群健康不是你新增的，不能修改：" + health.getFishName());
        }
        BeanUtils.copyProperties(healthDto,health);
        health.setStartTime(LocalDateTimeUtils.parseStringToDateTime(healthDto.getStartTime(), DatePattern.NORM_DATETIME_FORMATTER));
        health.setEndTime(LocalDateTimeUtils.parseStringToDateTime(healthDto.getEndTime(), DatePattern.NORM_DATETIME_FORMATTER));
        if(updateById(health)){
            //先删除
            sysRelationFileService.deleteFile(Arrays.asList(healthDto.getId()),ServiceType.HEALTH);
            //附件保存
            sysRelationFileService.saveFile(healthDto.getFileId(),health.getId(),ServiceType.HEALTH);
            log.info(StrUtil.format("【修改鱼群健康成功】操作人id：{}，修改目标health：{}", SecurityUtils.getCurrentUserId(), healthDto));
            return Result.success("修改成功！");
        };
        return Result.error("修改失败！");
    }

    @Override
    public void download(String fishName, HttpServletResponse response) throws IOException {
        Page page = new Page<>(-1, -1);
        List<HealthVo> records = healthMapper.getHealthList(page, fishName).getRecords();
        List<Map<String, Object>> list = new ArrayList<>();
        records.forEach(healthtVo -> {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("鱼的名称", healthtVo.getFishName());
            map.put("病情描述", healthtVo.getTransparency());
            map.put("数量", healthtVo.getNum());
            map.put("处理措施", healthtVo.getBiologicalContent());
            map.put("治疗结果", healthtVo.getTreatmentOutcome());
            map.put("发病开始时间", LocalDateTimeUtil.format(healthtVo.getStartTime(), DatePattern.NORM_DATETIME_FORMATTER));
            map.put("发病结束时间", LocalDateTimeUtil.format(healthtVo.getEndTime(), DatePattern.NORM_DATETIME_FORMATTER));
            map.put("创建时间", LocalDateTimeUtil.format(healthtVo.getCreatedTime(), DatePattern.NORM_DATETIME_FORMATTER));
            list.add(map);
        });
        Map<Integer, Integer>widthMap = new HashMap<>();
        FileUtils.downloadExcel(list,widthMap, response);
    }
}
